//引入数据库模块
const { connection, requestQuery } = require('../database/db');
//cnpm install moment --save 格式化时间
const moment = require('moment')
//加密模块
var bcrypt = require('bcryptjs');
const salt = bcrypt.genSaltSync(10);
//引入token模块
const JWT = require('../utils/token')

exports.userList = async (req, res) => {
    //get传值req.query {page:1,size:10}
    console.log(req.query);
    let page = req.query.page || 1;
    let size = req.query.size || 10;
    let sort = req.query.sort || 'ASC';
    let index = (page - 1) * size;
    //countSql 查询可用用户总数
    let countSql = `SELECT COUNT(*) FROM users WHERE is_show=1`
    let countResult = await requestQuery(countSql);
    let total = countResult[0]['COUNT(*)']
    //列表sql
    let userSql = `SELECT * FROM users WHERE is_show=1 ORDER BY sort ${sort} LIMIT ${index},${size}`
    let userlistData = await requestQuery(userSql)
    let totalPage = Math.ceil(total / size);
    res.json({
        status: 200,
        total: total,
        page: page,
        size: size,
        sort: sort,
        data: userlistData,
        totalpage: totalPage
    })
}
//用户注册
// post
exports.userRegister = (req, res) => {
    console.log(req.body)
    let user_name = req.body.user_name
    let user_password = req.body.user_password
    let phone = req.body.phone
    //格式化时间
    let nowTime = moment().format('YYYY-MM-DD HH:mm:ss')
    //用户名和手机号不能重复添加
    //先查询用户名是否存在
    let user_name_sql = `SELECT user_name from users WHERE user_name=? AND is_show=1`
    connection.query(user_name_sql, user_name, (err, result_name) => {
        if (err) {
            return res.json({
                msg: "用户注册失败1",
                status: 1001,
                data: err
            })
        }
        console.log(result_name); //得到一个数组
        //如果result_name是一个空数组,说明该用户名可用
        if (result_name == "") {
            //如果条件成立说明该用户名可用
            //在判断手机号是否存在
            let phone_sql = `select phone from users where phone=? AND is_show=1`;
            connection.query(phone_sql, phone, (err, result_phone) => {
                if (err) {
                    return res.json({
                        msg: "用户注册失败2",
                        status: 1002,
                        data: err
                    })
                }
                if (result_phone == "") {
                    //如果条件成立说明手机号可用
                    //手机号可用可以写入数据库
                    let register_sql = `INSERT INTO users SET user_name=?,user_password=?,phone=?,is_show=1,create_time="${nowTime}"`
                    let hashPassword = bcrypt.hashSync(user_password, salt)
                    connection.query(register_sql, [user_name, hashPassword, phone], (err, data) => {
                        if (err) {
                            return res.json({
                                msg: "用户注册失败3",
                                status: 1003,
                                data: err
                            })
                        }
                        console.log(data);
                        if (data.affectedRows == 1) {
                            return res.json({
                                msg: '恭喜您注册成功，可以放心购物了',
                                status: 200,
                                data: data
                            })
                        } else {
                            return res.json({
                                msg: "用户注册失败4",
                                status: 1004,
                                data: err
                            })
                        }
                    })
                } else {
                    return res.json({
                        msg: "该手机号存在，请换个手机号重新注册",
                        status: 1005
                    })
                }
            })
        } else {
            //说明用户名不可用
            return res.json({
                msg: "该用户名存在，请换个用户名重新注册",
                status: 1006
            })
        }
    })
};

//用户登录
exports.Login = (req, res) => {
    let user_name = req.body.user_name;
    let user_password = req.body.user_password
    let user_name_sql = `SELECT user_name,user_password from users WHERE user_name=? AND is_show=1`
    connection.query(user_name_sql, [user_name], (err, data) => {
        if (err) {
            return res.json({
                msg: '数据库查询失败',
                status: 5001,
                data: err
            })
        }
        if (data.length == 0) {
            return res.json({
                msg: '该用户不存在,请注册用户名',
                status: 404
            })
        } else {
            console.log(data);
            let check_user_password = bcrypt.compareSync(req.body.user_password, data[0].user_password);
            console.log(check_user_password);
            if (!check_user_password) {
                return res.json({
                    msg: "密码错误,请重新输入",
                    status: 404
                })
            } else {
                let token = JWT.createToken({
                    user_name: user_name,
                    isLogin: true
                })
                JWT.checkToken(token).then(result => {
                    console.log(111);
                    console.log(result);
                    console.log(222);
                })
                return res.json({
                    msg: '登陆成功',
                    status: 200,
                    data: data,
                    token: token
                })
            }
        }
    })
}